from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.datawarehouse import DatawarehouseConfig
from app.schemas.datawarehouse import (
    DatawarehouseConfigCreate,
    DatawarehouseConfigUpdate,
    DatawarehouseConfigPublic,
    DatawarehouseConfig as DatawarehouseConfigSchema
)

router = APIRouter(prefix="/datawarehouse", tags=["数据仓库配置"])


@router.get("/configs", response_model=List[DatawarehouseConfigPublic])
def get_datawarehouse_configs(
    skip: int = 0,
    limit: int = 100,
    active_only: bool = True,
    db: Session = Depends(get_db)
):
    """获取数据仓库配置列表"""
    query = db.query(DatawarehouseConfig)
    if active_only:
        query = query.filter(DatawarehouseConfig.is_active == True)
    
    configs = query.offset(skip).limit(limit).all()
    return configs


@router.get("/configs/{config_id}", response_model=DatawarehouseConfigPublic)
def get_datawarehouse_config(config_id: int, db: Session = Depends(get_db)):
    """获取单个数据仓库配置"""
    config = db.query(DatawarehouseConfig).filter(DatawarehouseConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="数据仓库配置未找到")
    return config


@router.get("/configs/default", response_model=DatawarehouseConfigPublic)
def get_default_datawarehouse_config(db: Session = Depends(get_db)):
    """获取默认数据仓库配置"""
    config = db.query(DatawarehouseConfig).filter(
        DatawarehouseConfig.is_default == True,
        DatawarehouseConfig.is_active == True
    ).first()
    if not config:
        raise HTTPException(status_code=404, detail="未找到默认数据仓库配置")
    return config


@router.post("/configs", response_model=DatawarehouseConfigPublic)
def create_datawarehouse_config(
    config: DatawarehouseConfigCreate,
    db: Session = Depends(get_db)
):
    """创建数据仓库配置"""
    # 检查名称是否已存在
    existing = db.query(DatawarehouseConfig).filter(DatawarehouseConfig.name == config.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="配置名称已存在")
    
    # 如果设置为默认，取消其他默认配置
    if config.is_default:
        db.query(DatawarehouseConfig).update({"is_default": False})
    
    db_config = DatawarehouseConfig(**config.dict())
    db.add(db_config)
    db.commit()
    db.refresh(db_config)
    return db_config


@router.put("/configs/{config_id}", response_model=DatawarehouseConfigPublic)
def update_datawarehouse_config(
    config_id: int,
    config_update: DatawarehouseConfigUpdate,
    db: Session = Depends(get_db)
):
    """更新数据仓库配置"""
    db_config = db.query(DatawarehouseConfig).filter(DatawarehouseConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="数据仓库配置未找到")
    
    # 如果设置为默认，取消其他默认配置
    if config_update.is_default:
        db.query(DatawarehouseConfig).filter(DatawarehouseConfig.id != config_id).update({"is_default": False})
    
    update_data = config_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_config, field, value)
    
    db.commit()
    db.refresh(db_config)
    return db_config


@router.delete("/configs/{config_id}")
def delete_datawarehouse_config(config_id: int, db: Session = Depends(get_db)):
    """删除数据仓库配置"""
    db_config = db.query(DatawarehouseConfig).filter(DatawarehouseConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="数据仓库配置未找到")
    
    db.delete(db_config)
    db.commit()
    return {"message": "配置删除成功"}


@router.post("/configs/{config_id}/test-connection")
def test_datawarehouse_connection(config_id: int, db: Session = Depends(get_db)):
    """测试数据仓库连接"""
    config = db.query(DatawarehouseConfig).filter(DatawarehouseConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="数据仓库配置未找到")
    
    # TODO: 实现具体的连接测试逻辑
    # 这里可以根据配置类型(doris, clickhouse等)使用相应的客户端进行连接测试
    
    return {
        "success": True,
        "message": "连接测试成功",
        "config_name": config.name,
        "config_type": config.type
    } 